<template>
  <div class="task-container">
    <div class="tab-list">
      <el-button type="primary" class="add-btn" @click="dialogShow = true">新建</el-button>
      <el-badge v-show="badge" :value="chargeNum" :max="99" class="badge-style"></el-badge>
      <el-tabs v-model="activeName" @tab-click="handleClick">
        <el-tab-pane label="我负责" name="1">
          <div v-show="emptyListFlag&&!taskLoading">
            <div class="task-left clearfix">
							<el-scrollbar class="scroll-height-left">
								<component :is="leftList" :taskList="taskList" @taskDetail="taskDetail"></component>
							</el-scrollbar>
            </div>
            <div class="task-right clearfix" ref="taskRight" v-show="emptyListFlag">
              <div class="task-right-header">
                <span>任务编号：{{taskNo}}</span>
                <el-button class="header-btn" @click="dialogtransferVisible = true">转派</el-button>
                <el-button class="header-btn" @click="complateTask(1)" type="primary">完成</el-button>
              </div>
              <div class="task-right-content">
								<el-scrollbar class="scroll-height">
									<div class="right-content-container clearfix">
										<component :is="centerList" ref="taskInfo1" @getList="getList" :taskInfo="taskInfoList" :showDetailAttach="1"></component>
										<component :is="rightList" :taskInfo="taskInfoList"></component>
									</div>
								</el-scrollbar>
              </div>
            </div>
          </div>
          <div v-show="!emptyListFlag&&!taskLoading">
            <component :is="emptyTask"></component>
          </div>
        </el-tab-pane>
        <el-tab-pane label="我协同" name="2">
          <div v-show="emptyListFlag&&!taskLoading">
            <div class="task-left clearfix">
							<el-scrollbar class="scroll-height-left">
								<component :is="leftList" :taskList="taskList" @taskDetail="taskDetail"></component>
							</el-scrollbar>
            </div>
            <div class="task-right clearfix" ref="taskRight" v-show="emptyListFlag">
              <div class="task-right-header">
                <span>任务编号：{{taskNo}}</span>
              </div>
              <div class="task-right-content">
								<el-scrollbar class="scroll-height">
									<div class="right-content-container clearfix">
										<component :is="centerList" ref="taskInfo2" @getList="getList" :taskInfo="taskInfoList" :showDetailAttach="2"></component>
										<component :is="rightList" :taskInfo="taskInfoList"></component>
									</div>
								</el-scrollbar>
              </div>
            </div>
          </div>
          <div v-show="!emptyListFlag&&!taskLoading">
            <component :is="emptyTask"></component>
          </div>
        </el-tab-pane>
        <el-tab-pane label="我创建" name="3">
          <div v-show="emptyListFlag&&!taskLoading">
            <div class="task-left clearfix">
							<el-scrollbar class="scroll-height-left">
								<component :is="leftList" :taskList="taskList" @taskDetail="taskDetail"></component>
							</el-scrollbar>
            </div>
            <div class="task-right clearfix" ref="taskRight" v-show="emptyListFlag">
              <div class="task-right-header">
                <span>任务编号：{{taskNo}}</span>
              </div>
              <div class="task-right-content">
								<el-scrollbar class="scroll-height">
									<div class="right-content-container clearfix">
										<component :is="centerList" ref="taskInfo3" @getList="getList" :taskInfo="taskInfoList" :showDetailAttach="3"></component>
										<component :is="rightList" :taskInfo="taskInfoList"></component>
									</div>
								</el-scrollbar>
              </div>
            </div>
          </div>
          <div v-show="!emptyListFlag&&!taskLoading">
            <component :is="emptyTask"></component>
          </div>
        </el-tab-pane>
      </el-tabs>
    </div>
    <el-dialog
      title=""
      class="task-dialog"
      :visible.sync="dialogShow"
      width="745px"
      :show-close="false"
      :modal="true"
      top="66px"
      @close="resetTmp"
      :close-on-click-modal="false">
      <div class="task-dialog-header">
        <div class="header-left">
          新建任务
        </div>
        <div class="header-right">
          <el-button size="small" @click="dialogShow = false">取 消</el-button>
          <el-button size="small" type="primary" @click="addHandle">发 布</el-button>
        </div>
        <div class="clearfix"></div>
      </div>
      <el-form :rules="rules" class="dialog-form" ref="forms" :model="form" label-width="100px">
        <div class="task-dialog-title">责任和日期</div>
        <el-col :span="11">
          <el-form-item label="执行人" prop="exec_user_id">
            <el-select v-model="form.exec_user_id" filterable remote :remote-method="getExecList" placeholder="请输入姓名" @change="clearSelectList" @focus="clearSelectList">
              <el-option
                v-for="item in execList"
                :key="item.id"
                :label="item.username"
                :value="item.id"
                :loading="execLoading">
              </el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="11" :offset="1">
          <el-form-item label="协同人">
            <el-select v-model="form.cooper_user_id" :clearable="true" filterable remote :remote-method="getCoopList" placeholder="请输入姓名" @change="clearSelectList" @focus="clearSelectList">
              <el-option
                v-for="item in coopList"
                :key="item.id"
                :label="item.username"
                :value="item.id"
                :loading="coopLoading">
              </el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <div class="clearfix"></div>
        <el-col :span="23">
          <el-form-item label="选择日期" prop="date_time">
            <el-date-picker
              v-model="form.date_time"
              type="datetimerange"
              range-separator="-"
              start-placeholder="计划日期"
              end-placeholder="截止日期"
              :editable="false"
              :clearable="false"
              align="right"
              @change="setTime()"
              :picker-options="pickerOptions"
              value-format="yyyy-MM-dd HH:mm:ss">
            </el-date-picker>
          </el-form-item>
        </el-col>
        <div class="clearfix"></div>
        <div class="task-dialog-title">委派内容</div>
        <el-col :span="23">
          <el-form-item label="任务主题" prop="task_subject">
            <el-input v-model="form.task_subject" maxlength='40' placeholder="请输入任务简介，限字40"></el-input>
          </el-form-item>
          <el-form-item label="任务内容" prop="task_content">
            <el-input type="textarea" maxlength="1000" placeholder="请输入内容，限字1000" v-model="form.task_content"></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="11">
          <el-form-item label="添加患者">
            <el-select v-model="form.card_id" :clearable="true" filterable remote :remote-method="getCardList" placeholder="请输入姓名" @change="clearSelectList" @focus="clearSelectList">
              <el-option
                v-for="item in cardList"
                :key="item.id"
                :label="item.username"
                :value="item.id"
                :loading="cardLoading"
                :clearable="true">
              </el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="16">
          <el-form-item label="上传附件">
            <el-upload
            class="upload-demo"
            ref="upload"
            action=""
            :limit="5"
            :on-change="beforeUpload"
            :before-remove="beforeRemove"
						:on-exceed="handleExceed"
            :file-list="dialogFileList"
            :auto-upload="false">
              <el-button :slot="trigger" size="small" type="primary">本地上传</el-button>
              <div slot="tip" class="el-upload__tip">最多各传5个附件，每个不超过3M</div>
            </el-upload>
						<!--<div>
							<el-popover
								popper-class="mobile-popper"
								placement="top"
								title="请扫描二维码上传照片"
								width="180"
								trigger="click"
								v-model="mobileDialog">
								<div style="text-align:center">
									<img :src="qrcode" />
								</div>
								<el-button slot="reference" class="mobile-button" v-bind:class="{'mobile-left': trigger === ''}"  size="small" type="primary" @click="mobileHandle()">手机上传</el-button>
							</el-popover>
						</div>-->
            <el-button v-bind:class="{'mobile-left': trigger === ''}" class="mobile-button" size="small" type="primary" @click="mobileHandle()">手机上传</el-button>
            <ul class="el-upload-list el-upload-list--text">
              <li tabindex="0" class="el-upload-list__item is-ready" v-for="(item, index) of piclist.files" v-bind:key="index">
                <a class="el-upload-list__item-name">
                  <i class="el-icon-document"></i>{{piclist.files_name[index]}}
                </a>
                <label class="el-upload-list__item-status-label">
                  <i class="el-icon-upload-success el-icon-circle-check"></i>
                </label>
                <i class="el-icon-close" @click="deleteImg(index)"></i>
              </li>
            </ul>
          </el-form-item>
        </el-col>
        <div class="clearfix"></div>
      </el-form>
    </el-dialog>
    <el-dialog
      width="300px"
      title="扫描二维码上传"
      :visible.sync="mobileDialog"
      append-to-body>
      <div style="text-align:center">
        <img :src="qrcode" />
      </div>
    </el-dialog>
    <!--转派dialog-->
    <el-dialog title="转派" :visible.sync="dialogtransferVisible" width="420px" class="transfer-dialog" @close="closeTransferDialog">
      <el-form :model="transferForm" :rules="transferRule" ref="transferForm">
        <el-form-item label="执行人" label-width="80px" style="letter-spacing:3px;" prop="name">
          <el-select v-model="transferForm.name" :clearable="true" filterable remote :remote-method="getExecList" placeholder="请输入姓名" @change="clearSelectList" @focus="clearSelectList">
            <el-option
              v-for="item in execList"
              :key="item.id"
              :label="item.username"
              :value="item.id"
              :loading="execLoading">
            </el-option>
          </el-select>
        </el-form-item>
        <!--<el-form-item label="" label-width="80px" style="margin-top:-18px;">
          <span style="color:#c0c4cc;letter-spacing:0px;">最多1名</span>
        </el-form-item>-->
        <el-form-item label="转派说明" label-width="80px" prop="explain">
          <el-input type="textarea" v-model="transferForm.explain" auto-complete="off" maxlength="200" placeholder="请输入内容，限字200"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogtransferVisible = false">取 消</el-button>
        <el-button type="primary" @click="transferSubmit">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>
<style>
  .clearfix:before,.clearfix:after{
    content:"";
    display:block;
    clear:both;
    height:0;
  }
	.mobile-popper{
		background-color: #333333;
		border:0;
	}
	.mobile-popper .el-popover__title{
		text-align: center;
		color:#fff;
		margin-bottom: 15px;
		margin-top:10px;
	}
	.mobile-popper[x-placement^=top] .popper__arrow::after{
		border-top-color:#333333;
	}
</style>
<style scoped src="./components/task.css"></style>
<script>
  import leftList from './components/list'
  import centerList from './components/detail'
  import rightList from './components/history'
  import emptyTask from './components/emptyTask'
  import {chargeList, cardList} from '@/api/user'
  import {addTask, taskList, taskInfo, getSignToken, getMobileImg, deleteMobileImg, taskTransfer} from '@/api/task'
  import {getToken, setCookie, getCookie, removeCookie} from '@/utils/auth'
  import QRCode from 'qrcode'
  export default {
    data () {
      // 数据校验
      var checkExecUserId = (rule, value, callback) => {
        if (!value) {
          return callback(new Error('发起人姓名不能为空'))
        } else {
          callback()
        }
      }
      var checkTaskSubject = (rule, value, callback) => {
        if (!(value.trim())) {
          this.form.task_subject = ''
          return callback(new Error('任务主题不能为空'))
        } else {
          callback()
        }
      }
      var checkTaskContent = (rule, value, callback) => {
        if (!(value.trim())) {
					this.form.task_content = ''
          return callback(new Error('任务内容不能为空'))
        } else {
          callback()
        }
      }
      var checkDateTime = (rule, value, callback) => {
        if (!value || value === []) {
          return callback(new Error('任务执行时间不能为空'))
        } else {
          callback()
        }
      }
			var checkTransferExplain = (rule, value, callback) => {
				if (!(value.trim())) {
					this.transferForm.explain = ''
					return callback(new Error('请输入转派说明'))
				} else {
					callback()
				}
			}
      return {
        leftList: leftList,
        centerList: centerList,
        rightList: rightList,
        emptyTask: emptyTask,
        activeName: '1',
        taskList: [],
        taskId: '',
        taskNo: '',
        taskInfoList: {
          taskdetail: {
            attach: []
          },
          process: {}
        },
        chargeNum: '',
        badge: false,
        emptyListFlag: true,
        taskLoading: true,
        showDetailAttach: false,
        dialogtransferVisible: false,
        dialogShow: false,
        mobileDialog: false,
        dialogFileList: [],
        trigger: 'trigger',
        form: {
          exec_user_id: '',
          cooper_user_id: '',
          date_time: '',
          plan_time: '',
          end_time: '',
          task_subject: '',
          task_content: '',
          card_id: '',
          card_username: ''
        },
        rules: {
          exec_user_id: [{ required: true, validator: checkExecUserId, trigger: 'blur' }],
          task_subject: [{ required: true, validator: checkTaskSubject, trigger: 'blur' }],
          task_content: [{ required: true, validator: checkTaskContent, trigger: 'blur' }],
          date_time: [{ required: true, validator: checkDateTime, trigger: 'blur' }]
        },
        qrcode: '',
        accept: [], // 允许上传的类型
        execLoading: false,
        execList: {}, // 执行人列表
        coopLoading: false,
        coopList: {}, // 执行人列表
        cardLoading: false,
        cardList: {}, // 执行人列表
        piclist: [],
        transferForm: {
          name: '',
          explain: ''
        },
        transferRule: {
          name: [{ required: true, message: '请选择执行人', trigger: 'change' }],
          explain: [
            { required: true, validator: checkTransferExplain, trigger: 'blur' },
            { max: 200, message: '长度在200个字符以内', trigger: 'blur' }
          ]
        },
				execId: '',
        pickerOptions: {
          disabledDate(time) {
            if (time.getTime() < Date.now() - 86400 * 1000) {
              return true
            } else if (time.getTime() > Date.now() + 86400 * 1000 * 6) {
              return true
            }
            // return time.getTime() < Date.now() - 86400
          }
        }
      }
    },
    created () {
			// 报警任务警示红点是否显示
			this.initTask()
      this.getTaskList()
      removeCookie('sign')
      // var d = new Date()
      // var date = d.getFullYear() + '-' + (d.getMonth() + 1) + '-' + d.getDate() + ' ' + d.getHours() + ':' + d.getMinutes() + ':' + d.getSeconds()
      // this.form.date_time = [date, date]
    },
    mounted () {
    },
    methods: {
      // 切换标签页
      handleClick() {
        this.getTaskList()
      },
      // 获取手机上传图片列表
      getMobileImg () {
        var tok = getCookie('sign')
        if (tok) {
          getMobileImg({sign: tok}).then((response) => {
            this.piclist = response.data
            setTimeout(() => {
              this.getMobileImg()
            }, 5000)
          })
        }
      },
      getList () {
        this.initTask()
        this.getTaskList()
      },
			initTask () {
				taskList(Object.assign({}, {'tasktype': 2, 'usertype': 1})).then(response => {
					if (response.data.list.length > 0) {
						this.$store.dispatch('setShowWarnDot', true)
						return false
					} else {
						taskList(Object.assign({}, {'tasktype': 2, 'usertype': 2})).then(response => {
							if (response.data.list.length > 0) {
								this.$store.dispatch('setShowWarnDot', true)
								return false
							} else {
								taskList(Object.assign({}, {'tasktype': 2, 'usertype': 3})).then(response => {
									if (response.data.list.length > 0) {
										this.$store.dispatch('setShowWarnDot', true)
										return false
									} else {
										this.$store.dispatch('setShowWarnDot', false)
									}
								})
							}
						})
					}
				})
			},
      // 获取任务列表
      getTaskList() {
        this.taskLoading = true
        taskList(Object.assign({}, {'tasktype': 1, 'usertype': this.activeName})).then(response => {
          if (this.activeName === '1') {
            if (response.data.list.length > 0) {
              this.badge = true
              this.chargeNum = response.data.list.length
							this.$store.dispatch('setDealNum', this.chargeNum)
							this.$store.dispatch('setShowDealDot', true)
            } else {
              this.badge = false
							this.$store.dispatch('setShowDealDot', false)
							this.$store.dispatch('setDealNum', '')
            }
          }
          this.taskList = response.data.list
          this.taskLoading = false
          if (this.taskList.length > 0) {
            this.emptyListFlag = true
            this.taskId = response.data.list[0].id
            this.taskDetail(this.taskId)
          } else {
            this.taskInfoList = {
              taskdetail: {
                attach: []
              },
              process: {}
            }
            this.emptyListFlag = false
          }
        })
      },
      clearHandle () {
        this.cardList = []
      },
      // 获取任务详情
      taskDetail(taskNo) {
        this.taskId = taskNo
        taskInfo(Object.assign({}, {'task_id': this.taskId})).then(response => {
          this.taskInfoList = response.data
          this.taskInfoList.taskdetail.attach_names = JSON.parse(this.taskInfoList.taskdetail.attach_names)
          this.taskInfoList.taskdetail.attach = JSON.parse(this.taskInfoList.taskdetail.attach)
          this.taskNo = this.taskInfoList.taskdetail.task_no
          this.$refs['taskInfo1'].complate.remark = '' // 初始化组件数据
          this.$refs['taskInfo2'].complate.remark = '' // 初始化组件数据
          this.$refs['taskInfo3'].complate.remark = '' // 初始化组件数据
					this.$refs['taskInfo1'].dialogFileList = [] // 初始化本地上传附件
					this.$refs['taskInfo1'].piclist = [] // 初始化手机上传附件
					this.$refs['taskInfo1'].clearVal()
        })
      },
      // 删除临时图片
      deleteImg (index) {
        var url = this.piclist.files[index]
        var id = this.piclist.id
        deleteMobileImg({id: id, img_url: url}).then((response) => {
          this.piclist.files.splice(index, 1)
          this.piclist.files_name.splice(index, 1)
        })
      },
      getExecList (query) {
        if (this.dialogShow) {
          if (this.form.exec_user_id === '' && this.form.cooper_user_id === '') {
						this.execId = ''
					} else if (this.form.exec_user_id === '' && this.form.cooper_user_id !== '') {
						this.execId = this.form.cooper_user_id
					}
				}
				if (this.dialogtransferVisible) {
					this.execId = this.taskInfoList.taskdetail.exec_user_id
				}
        if (query !== '') {
					this.execList = []
          this.execLoading = true
          chargeList({kw: query, exec_id: this.execId}).then((response) => {
            this.execLoading = false
            this.execList = response.data
          })
        } else {
          this.execList = []
        }
      },
      getCoopList (query) {
				if (this.dialogShow) {
					if (this.form.exec_user_id === '' && this.form.cooper_user_id === '') {
						this.execId = ''
					} else if (this.form.exec_user_id !== '' && this.form.cooper_user_id === '') {
						this.execId = this.form.exec_user_id
					}
				}
        if (query !== '') {
          this.coopLoading = true
					this.coopList = []
          chargeList({kw: query, exec_id: this.execId}).then((response) => {
            this.coopLoading = false
            this.coopList = response.data
          })
        } else {
          this.coopList = []
        }
      },
      getCardList (query) {
        if (query !== '') {
          this.cardLoading = true
					this.cardList = []
          cardList({kw: query}).then((response) => {
            this.cardLoading = false
            this.cardList = response.data
          })
        } else {
          this.cardList = []
        }
      },
			// 清空下拉选项
			clearSelectList () {
				this.cardList = []
				this.coopList = []
				this.execList = []
			},
      mobileHandle () {
        var obj = this
        var sign = getCookie('sign')
        if (!sign) {
          getSignToken().then((response) => {
            setCookie('sign', response.data.token, 0.3)
            this.mobileHandle()
          })
        } else {
          this.getMobileImg()
          QRCode.toDataURL(process.env.BASE_URL + '/mobile/upload?sign=' + sign, {
            width: 200,
            height: 200
          }, function(err, url) {
            if (err) throw err
            obj.qrcode = url
          })
          this.mobileDialog = true
        }
      },
      addHandle () {
        this.$refs['forms'].validate((valid) => {
          if (valid) {
            var fd = new FormData()
            for (const k in this.$refs.upload.$refs['upload-inner'].fileList) {
              fd.append('file[]', this.$refs.upload.$refs['upload-inner'].fileList[k].raw)
            }
            fd.append('token', getToken()) // 用户token
            fd.append('exec_user_id', this.form.exec_user_id)
            fd.append('cooper_user_id', this.form.cooper_user_id)
            fd.append('plan_time', this.form.plan_time)
            fd.append('end_time', this.form.end_time)
            fd.append('task_subject', this.form.task_subject)
            fd.append('task_content', this.form.task_content)
            fd.append('card_id', this.form.card_id)
            // 如果有手机附件
            if (this.piclist.files !== undefined) {
              for (const key in this.piclist.files) {
                fd.append('mobile_file[]', this.piclist.files[key])
              }
            }
            addTask(fd).then(response => {
              this.$message({
                message: '新建任务成功!',
                type: 'success',
                onClose: () => {
                  this.$nextTick(() => {
                    this.$refs['forms'].clearValidate()
                    this.dialogShow = false
                    this.getTaskList() // 重新获取列表
                  })
                }
              })
            })
          }
        })
      },
      beforeUpload(file, fileList) {
        const isJPG = this.accept.indexOf(file.raw.type) // 判断是否是图片
        const isLt3M = file.size / 1024 / 1024 <= 3
        if (!isLt3M) {
          fileList.pop()
          this.$message.error('上传附件不能大于3MB!')
        }
        /* if (fileList.length >= 5) {
          this.trigger = ''
        } */
        return isJPG && isLt3M
      },
      beforeRemove () {
        this.trigger = 'trigger'
      },
			handleExceed () {
				this.$message.warning('本地上传最多只能上传5个附件')
			},
      resetTmp () {
        // var d = new Date()
        // var date = d.getFullYear() + '-' + (d.getMonth() + 1) + '-' + d.getDate() + ' ' + d.getHours() + ':' + d.getMinutes() + ':' + d.getSeconds()
        this.form.exec_user_id = ''
        this.form.cooper_user_id = ''
        // this.form.date_time = [date, date]
        this.form.date_time = ''
        this.form.plan_time = ''
        this.form.end_time = ''
        this.form.task_subject = ''
        this.form.task_content = ''
        this.form.card_id = ''
        this.form.card_username = ''
        this.piclist = [] // 手机附件
				this.dialogFileList = [] // 本地上传附件
				this.execList = []
				this.coopList = []
				this.cardList = []
        removeCookie('sign')
        this.$nextTick(() => {
          this.$refs['forms'].clearValidate()
        })
      },
      setTime () {
        this.form.plan_time = this.form.date_time[0]
        this.form.end_time = this.form.date_time[1]
      },
      // 打开转派弹窗
      closeTransferDialog() {
        this.transferForm = {
          name: '',
          explain: ''
        }
				this.execList = []
        this.$nextTick(() => {
          this.$refs['transferForm'].clearValidate()
        })
      },
      // 转派确定按钮
      transferSubmit() {
        this.$refs['transferForm'].validate((valid) => {
          if (valid) {
            taskTransfer(Object.assign({}, {'task_id': this.taskId, 'to_user_id': this.transferForm.name, 'remark': this.transferForm.explain})).then(response => {
              this.dialogtransferVisible = false
              this.getTaskList()
              this.$message({
                message: '转派成功',
                type: 'success'
              })
            })
          } else {
            return false
          }
        })
      },
      // 完成任务
      complateTask (id) {
				this.$refs['taskInfo' + id].complateTask()
      }
    }
  }
</script>
